import regeneratorRuntime from '../../utils/runtime.js'
import QRCode from '../../utils/qrcode.js'
const app = getApp()
let _this;

const cache = {}

Page({
  // 页面的初始数据
  data: {
    userInfo : {},
    nickname : '',
    context:'',
    isEdit:false,
    shareModal : false,
    count : {
      countCity : 0,
      countCountry : 0,
      countUser : 0,
    },
    banners: {
      count : 0,
      data : [],
    },
    enableMoney : false,
    bannerHeight:124,
    indicatorDots: false,
    autoplay: true,
    interval: 5000,
    duration: 1000,
    indicatorColor:'rgba(255,255,255,.3)',
    indicatorActiveColor:'rgba(255,255,255,.9)',

    isShowAlert:false,
    isShowShare : false,
    payText:'祝：大吉大利，财源滚滚',
    freeText: '祝：大吉大利，财源滚滚',
    list:[
      {text:"369向上走",number:'3.69',checked:true},
      {text:"一帆风顺",number:'6.66',checked:false},
      {text:"恭喜发财",number:'8.88',checked:false},
    ],
  },
  btnShowAlert:(e)=>{
    _this.setData({isShowAlert:!_this.data.isShowAlert})
  },
  btnChoose:(e)=>{
    let idx=e.currentTarget.dataset.id;
    let temp=_this.data.list;
    temp.forEach((item,index)=>{
      if (index==idx) {
        item.checked=true
      }else{
        item.checked=false
      }
    })
    _this.setData({list:temp})
  },
  onLoad: function (options) {
    cache.cid = options.id || app.globalData.shareId
    _this=this;
    let userID = app.getGlobalData('ID')
    let userInfo = app.getGlobalData('userInfo')
    _this.setData({ userID: userID })
    _this.setData({ userInfo: userInfo })
    app.GET('/api/user/count', {}, function (data) { _this.setData({ count: data.data }) })
    app.GET('/api/template/', {}, function (data) { _this.setData({ payText: data.data, freeText: data.data }) })
    app.GET('/api/article/', { id: cache.cid || '', user : userID || '' }, async(data) => {
      _this.setData({ ...data.data})
    })
    app.GET('/api/setting/s', '', (data) => {
      _this.setData({ enableMoney : data.data })
    })
    app.GET('/api/article/banners', {}, function (data) { _this.setData({ banners: data.data }) })
  },
  btnrefresh : function(){
    let userID = app.getGlobalData('ID')
    app.GET('/api/article/', {}, (data) => {  _this.setData({ ...data.data })  })
  },
  btnShowShare : function(){
    _this.setData({ isShowShare: !_this.data.isShowShare })
  },
  btnBlurTextarea : function(e){
    if (e.detail.value.length < 70) {
      this.setData({ payText: e.detail.value })
    }
  },
  closeShare : function(){
    this.setData({ shareModal : false })
  },
  paySubmit : function(){//付费祝福
    let selected = null
    _this.data.list.forEach((item, index) => {
      if (item.checked) { selected = item }
    })
    if (!selected) { app.showError('请选择许愿的类型') }
    let userID = app.getGlobalData('ID')
    let userInfo = app.getGlobalData('userInfo')
    let form = {
      user: userID,
      nickname: userInfo.nickName,
      avatarUrl: userInfo.avatarUrl,
      fee: selected.number,
      context: this.data.payText
    }
    app.POST('/api/article/submit', form, function (res) {
      console.log(res)
      wx.requestPayment({
        ...res.data.pay,
        success: async(payRes) => {
          _this.setData({ isShowAlert: !_this.data.isShowAlert })
          let draw = await _this.onDrawCavans(res.data.article.id, res.data.article.context)
          _this.setData({ ...res.data.article, shareImg: draw.tempFilePath, shareModal: true })
        },
        fail: function (res) { app.showError('支付失败') }
      })
    })
  },
  btnInputTextareaFree:function(e){
    if (e.detail.value.length < 70){
      this.setData({ freeText: e.detail.value })
    }
  },
  freeSubmit: function(){//免费祝福
    let userID = app.getGlobalData('ID')
    let userInfo = app.getGlobalData('userInfo')
    let form = {
      user: userID,
      nickname: userInfo.nickName,
      avatarUrl: userInfo.avatarUrl,
      fee : 0.00,
      context: this.data.freeText
    }
    app.POST('/api/article/submitFree', form, async(res) =>{
      _this.setData({ isShowShare: !_this.data.isShowShare})
      let draw = await _this.onDrawCavans(res.data.id, res.data.context)
      _this.setData({ ...res.data, shareImg: draw.tempFilePath, shareModal: true })
    })
  },
  saveShareImage: function (){
    let _this = this
    wx.authorize({
      scope: 'scope.writePhotosAlbum',
      success() {
        wx.saveImageToPhotosAlbum({
          filePath: _this.data.shareImg,
          success: function () {
            app.showSuccess('已保存至相册')
          }
        })
      }
    })
  },
  onDrawCavans : async function(code=0, text=''){
    let url = `${app.globalData.PROFILE_RECOVER_FLAG}?code=${code}`
    let background = app.getGlobalData('BACKGROUND')
    let avarta = app.getGlobalData('AVARTA')
    let userInfo = app.getGlobalData('userInfo')
    if (userInfo == null){ return; }
    let qrcode = await QRCode.api.draw(url, "qrcodeCanvas", 90, 90, 0, 0);
    const ctx = wx.createCanvasContext('shareCanvas')
    ctx.drawImage(background || 'https://zhufu.xingqiuribao.com/draw.jpg', 0, 0, 360, 600)
    ctx.drawImage(qrcode.tempFilePath, 135, 425, 90, 90)
    ctx.save();

    ctx.setTextAlign('center')
    ctx.setFillStyle('#9D8979')
    ctx.setFontSize(16)
    ctx.fillText(`携${_this.data.count.countCountry}个国家 ${_this.data.count.countCity}座城市 ${_this.data.count.countUser}位朋友 发来祝福`, 360 / 2, 113)


    let lineSize = text.length / 12
    let lineTop = lineSize >= 5 ? 210 : 220
    ctx.setTextAlign('center')
    ctx.setFillStyle('#3D3D3D')
    ctx.setFontSize(17)
    for (let i = 0; i < lineSize; i++){
      let line = text.substr(i * 12, 12)
      if (i == 4 && line.length == 12) { line = line.substr(0, 8) + "..."}
      if(i <= 4){
        ctx.fillText(line, 360 / 2, lineTop + (i * 22))
      }
    }
    
    let avatarurl_width = 50;    //绘制的头像宽度
    let avatarurl_heigth = 50;   //绘制的头像高度
    let avatarurl_x = 160;   //绘制的头像在画布上的位置
    let avatarurl_y = 20;   //绘制的头像在画布上的位置
    ctx.beginPath(); //开始绘制
    ctx.arc(avatarurl_width / 2 + avatarurl_x, avatarurl_heigth / 2 + avatarurl_y, avatarurl_width / 2, 0, Math.PI * 2, false);
    ctx.clip();
    ctx.drawImage(avarta || userInfo.avatarUrl, avatarurl_x, avatarurl_y, avatarurl_width, avatarurl_heigth)

    ctx.save();
    ctx.stroke()
    wx.showLoading({ title: '加载中' })
    return new Promise((resolve, reject) => {
      ctx.draw(false, () => {
        wx.canvasToTempFilePath({
          canvasId: 'shareCanvas',
          success(res) { resolve(res); wx.hideLoading(); },
          fail(res) { reject(res); wx.hideLoading(); }
        })
      })
    })
  },
  onShareAppMessage() {
    return {
      title: `${_this.data.nickname} 携${_this.data.count.countCountry}个国家${_this.data.count.countCity}座城市${_this.data.count.countUser}位朋友向您发来祝福`,
      path: '/pages/index/index?id=' + _this.data.id
    }
  }
})